import { t } from 'i18next'
import { Draggable, Droppable } from '@/plugins/dnd'
import React, { useLayoutEffect, useRef, useState } from 'react'
import {
	IconActionCallOption,
	IconActionCalling,
	IconActionMuteOption,
	IconStatusMute,
	IconStatusOffline,
	IconStatusVideoSrc,
	StyledPopup,
	AddIcon,
	ItemGhost,
} from './style'
import { Trigger, TriggerInstance } from '@kedacom/react-next'
import { useMccStore } from '@/pages/manager/store'
import { ListItemGhost } from '@/pages/manager/components'
import { VmpMember, VmpTypeEnum } from '@/api/manager/vmp/interface'
import shallow from 'zustand/shallow'
import { useSize } from '@kedacom/hooks'
import useLock from '@/hooks/useLock'
import { fetchCallOnlineMt, fetchMute } from '@/api/manager/actions'
import { IMcc } from '@/api/manager/type'
import { Meeting } from '@/api/manager/meeting'
import { Mt } from '@/api/manager/mt'
import { useTableAllStore } from '../../main/table/all/store'
import { useVmpTypeStore } from '../store.get'
import { mccAddMt } from '@/components/AddMt/store.trans'
interface MemberItemProps {
	index: number
	onDrop: (dataTransfer: object, index: number) => void
	member: VmpMember
	dataKey: number
	disabled: boolean
	noAddIcon: boolean
	onTypeSelect: (index: number, name: string, type: number, member: VmpMember) => void
	onClearVmpMember: (index: number) => void
}
export function MemberItem(props: MemberItemProps) {
	const { member, index, onDrop, disabled, noAddIcon, dataKey, onTypeSelect, onClearVmpMember } = props
	const meetingType = useMccStore((state) => state.mccInfo.meetingType)
	const useStore = useVmpTypeStore((state) => state.getStore())
	const { isCall, setCalling } = useStore((state) => {
		return {
			isCall: member.mt_key && state.callingMap[member.mt_key] ? state.callingMap[member.mt_key].isCall : false,
			setCalling: state.setCalling,
		}
	}, shallow)
	const [active, setActive] = useState(false)
	const triggerRef = useRef<TriggerInstance>(null)
	const [style_sheets, setStyleSheet] = useState<React.CSSProperties>({})
	const [status_sheets, setStatusSheet] = useState<React.CSSProperties>({})
	const refContainerMember = useRef<HTMLDivElement>(null)
	const { width = 0, height = 0 } = useSize(refContainerMember)
	useLayoutEffect(() => {
		if (height !== null) {
			if (member.member_type === 1) {
				if (Number(height) <= 56) {
					const _top = 56 - Number(height)
					const max_top = (Number(height) - 18) / 2
					if (_top < max_top) {
						setStyleSheet({ position: 'relative', top: `${_top}px` })
					} else {
						setStyleSheet({ position: 'relative', top: `${max_top}px` })
					}
				} else {
					setStyleSheet({})
					setStatusSheet({ top: '4px' })
				}
			}
			if (
				member.member_type === 2 ||
				member.member_type === 3 ||
				member.member_type === 6 ||
				member.member_type === 4 ||
				member.member_type === 7
			) {
				if (member.name) {
					if (Number(height) <= 54) {
						setStatusSheet({ top: '-2px' })
						setStyleSheet({ marginTop: `16px` })
					} else if (55 < Number(height) && Number(height) <= 65) {
						const _relative_top = 65 - Number(height) + 6
						const _top = _relative_top > 16 ? 16 : _relative_top
						setStyleSheet({ marginTop: `${_top}px` })
						setStatusSheet({ top: '4px' })
					} else {
						setStyleSheet({})
						setStatusSheet({ top: '4px' })
					}
				}
			}
		} else {
			setStyleSheet({})
			setStatusSheet({ top: '4px' })
		}
	}, [width, height])
	/**请求终端*/
	const handleFetchCallMt = () => {
		if (member.mt_key) {
			setCalling(member.mt_key)
			const getMtModel = useTableAllStore.getState().getMtModel
			const _item = getMtModel([member.mt_key])
			if (_item[0]) {
				if (!_item[0].mcc.status.isOnline) {
					const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
					fetchCallOnlineMt(meetingMoid, [_item[0].mcc])
				}
			} else {
				mccAddMt(
					[
						{
							name: member.name,
							accountType: member.account_type,
							account: member.account,
							e164: member.e164,
							interactiveMt: 1,
							oftenMt: 0,
						},
					],
					'',
					true
				)
			}
		}
	}
	// 取消终端哑音
	const handleOperateMtMute = useLock(async () => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		let mcc: IMcc
		if (member.mt_type === 7 || member.mt_type === 8) {
			//会议
			mcc = {
				isMt: true,
				account: member.account || '',
				mtKey: member.mt_key || '',
				mtIp: member.mt_ip,
				name: member.INITIAL_NAME || '',
			} as unknown as Meeting
		} else {
			mcc = {
				isMt: false,
				e164: member.e164 || '',
				mtid: member.mt_id,
				mtKey: member.mt_key || '',
				mtIp: member.mt_ip,
				name: member.INITIAL_NAME || '',
				confE164: member.conf_e164,
				account: member.account || '',
				accountType: member.account_type,
			} as unknown as Mt
		}
		await fetchMute(!!member.mute, meetingMoid, mcc)
	})
	const handleTypeSelect = (name: string, type: number) => {
		triggerRef.current?.close()
		onTypeSelect(index, name, type, member)
	}
	const renderPopUp = () => {
		return (
			<StyledPopup onClick={() => setActive(false)}>
				<div className="rc_box-menu" onClick={() => handleTypeSelect(t('会议轮询跟随'), 4)}>
					{member.member_type === 4 && <span className="select-icon" />}
					{t('会议轮询跟随')}
				</div>
				<div className="rc_box-menu" onClick={() => handleTypeSelect(t('发言方跟随'), 2)}>
					{member.member_type === 2 && <span className="select-icon" />}
					{t('发言方跟随')}
				</div>
				<div className="rc_box-menu" onClick={() => handleTypeSelect(t('管理方跟随'), 3)}>
					{member.member_type === 3 && <span className="select-icon" />}
					{t('管理方跟随')}
				</div>
				<div className="rc_box-menu" onClick={() => handleTypeSelect(t('内容共享跟随'), 7)}>
					{member.member_type === 7 && <span className="select-icon" />}
					{t('内容共享跟随')}
				</div>
				<div className="item-line"></div>
				<div className="rc_box-menu" onClick={() => handleTypeSelect(t('单通道轮询'), 6)}>
					{member.member_type === 6 && <span className="select-icon" />}
					{t('单通道轮询')}
				</div>
			</StyledPopup>
		)
	}
	const getMembersName = (item: VmpMember) => {
		if (item.member_type === 1)
			return (
				<div className="cur-mt" title={item.name}>
					{item.name}
				</div>
			) //会控指定直接显示名字
		//其他模式显示 模式+终端
		let dom = <div className="mode">{t(`${VmpTypeEnum[item.member_type]}`)}</div>
		if (item.name) {
			//有终端显示终端
			let _name =
				item.mt_type === 3 && item.account !== item.name ? item.name + '(' + item.account + ')' : item.name
			dom = (
				<>
					<div className="mode">{t(`${VmpTypeEnum[item.member_type]}`)}</div>
					<div className="cur-mt" title={_name}>
						{_name}
					</div>
				</>
			)
		}
		return dom
	}
	return (
		<div
			className={`vmp-list-item ${active ? 'active' : ''}`}
			onMouseLeave={() => setActive(false)}
			data-key={dataKey}
			ref={refContainerMember}
		>
			<Droppable onDrop={(dataTransfer) => onDrop(dataTransfer, index)}>
				{(setDroppableRef) => (
					<div
						ref={setDroppableRef}
						className={`vmp-drop-item ${
							(member.member_type === 1 ||
								member.member_type === 2 ||
								member.member_type === 3 ||
								member.member_type === 6) &&
							member.mt_key &&
							!member.online
								? 'vmp-drop-item-online'
								: ''
						}`}
					>
						{!isCall && (
							<div
								className="operate"
								onMouseLeave={() => {
									triggerRef.current?.close()
								}}
							>
								{(member.member_type === 1 ||
									member.member_type === 2 ||
									member.member_type === 3 ||
									member.member_type === 6) &&
									member.mt_key &&
									!member.online && <IconActionCallOption onClick={() => handleFetchCallMt()} />}
								{(member.member_type === 1 ||
									member.member_type === 2 ||
									member.member_type === 3 ||
									member.member_type === 6) &&
									member.mt_key &&
									!!member.online && (
										<IconActionMuteOption
											isOn={!!member.mute}
											onClick={() => handleOperateMtMute()}
										/>
									)}
								{!disabled && meetingType !== 2 && (
									<Trigger onClick={() => setActive(true)} ref={triggerRef} popup={renderPopUp()}>
										<span className="set"></span>
									</Trigger>
								)}
								{!disabled && member.member_type !== 0 && (
									<span className="delete" onClick={() => onClearVmpMember(index)}></span>
								)}
							</div>
						)}
						<Draggable
							className="vmp-drag-item"
							canDrag={member.member_type !== 0 && member.member_type !== 6 && !disabled}
							dataTransfer={{
								data: member,
								index: index,
								from: 'vmpItem',
							}}
							ghostRender={
								member.member_type === 1 ? (
									<ListItemGhost
										data={{
											portrait: member.portrait || '',
											accountType: member.account_type || 1,
											isMt: true,
											name: member.name || '',
											isPhone: false,
											isSimpleCascade: false,
											status: {
												isOnline: !!member.online,
												isManager: false,
											},
										}}
									/>
								) : (
									<ItemGhost>{t(`${VmpTypeEnum[member.member_type]}`)}</ItemGhost>
								)
							}
						>
							{member.member_type !== 0 ? (
								<div
									className={`_box_content ${
										(member.member_type === 1 ||
											member.member_type === 2 ||
											member.member_type === 3 ||
											member.member_type === 6) &&
										member.mt_key &&
										!member.online
											? '_box_content_online'
											: ''
									}`}
								>
									<div className="content" style={style_sheets}>
										<div className="text">{getMembersName(member)}</div>
									</div>
									{/* 呼叫状态 */}
									{isCall &&
										!member.online &&
										(member.member_type === 1 ||
											member.member_type === 2 ||
											member.member_type === 3 ||
											member.member_type === 6) &&
										member.mt_key && (
											<IconActionCalling className="mt_operation_calling" style={status_sheets} />
										)}
									{/* 状态展示 */}
									{!isCall && (
										<>
											{/* 视频源展示 */}
											{!!member.online &&
												(member.member_type === 1 ||
													member.member_type === 2 ||
													member.member_type === 3 ||
													member.member_type === 6) &&
												member.mt_key &&
												!member.video_src && (
													<IconStatusVideoSrc
														title={t('视频源')}
														className="mt_operation_videosrc"
														style={status_sheets}
													/>
												)}
											{/* 终端在线状态哑音展示 */}
											{!!member.online &&
												(member.member_type === 1 ||
													member.member_type === 2 ||
													member.member_type === 3 ||
													member.member_type === 6) &&
												member.mt_key && (
													<IconStatusMute
														isOn={!!member.mute}
														className="mt_operation_mute"
														style={status_sheets}
													/>
												)}
											{/* 终端离线状态展示 */}
											{!member.online &&
												(member.member_type === 1 ||
													member.member_type === 2 ||
													member.member_type === 3 ||
													member.member_type === 6) &&
												member.mt_key && (
													<IconStatusOffline
														className="mt_operation_online"
														style={status_sheets}
													/>
												)}
										</>
									)}
								</div>
							) : noAddIcon ? (
								<></>
							) : (
								<AddIcon />
							)}
						</Draggable>
					</div>
				)}
			</Droppable>
		</div>
	)
}
